<?php
require_once dirname(__FILE__)."/../../protected/config/connections.php";

function updateOrder($db, $user_id, $out_trade_no, $trade_no, $trade_status)
{
    try {
        $status = 0;
        $pdo = new PDO($db['connectionString'], $db['username'], $db['password']);
        $tablePrefix = $db['tablePrefix'];
        $stmt = $pdo->prepare('SELECT status FROM '.$tablePrefix.'order WHERE id = :id');
        if ($stmt->execute(array(':id' => $out_trade_no))) {
            if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
                $status = $row[0];
            }
        }
        
        $stmt->closeCursor();
        
        if ($status == 3 || $status == 4) {//SAVED, CANCEL
            //processed, do nothing
        } else if ($status == 1 || $status == 2) {//BOOKED, PAYING
            $pdo->beginTransaction();
            
            $stmt = $pdo->prepare('UPDATE '.$tablePrefix.'order SET status = 3, update_time = NOW(), update_user_id = :user_id WHERE id = :id');
            $stmt->execute(array(':id' => $out_trade_no, ':user_id' => $user_id));
            
            $stmt = $pdo->prepare('INSERT INTO '.$tablePrefix.
                    'order_payment (order_id, trade_no, trade_status, user_id, create_time) VALUES (:order_id, :trade_no, :trade_status, :user_id, NOW())');
            $stmt->execute(array(':order_id' => $out_trade_no, ':trade_no' => $trade_no,
                ':trade_status' => $trade_status, ':user_id' => $user_id));
            
            $pdo->commit();
        }
        
        return true;
    } catch (PDOException $e) {
        //if ($pdo->inTransaction()) {
            $pdo->rollBack();
        //}
        
        return false; //"Error!: " . $e->getMessage() . "<br/>";
    }
}

//testing code
$result = updateOrder($db, 0, '3', 'a', 'OK');
echo $result;